<?php

namespace MLM\Model\Generic;

class Error extends Object {

  const CODE_DEFAULT = 0;
  const DESCRIPTION_DEFAULT = 'OK';

  protected $_trace = array();

  public function __construct($code = self::CODE_DEFAULT, $description = self::DESCRIPTION_DEFAULT, $owner = null) {

    parent::__construct(
      array(
        'code' => $code,
        'description' => $description,
        'owner' => $owner,
      ),
      array(
        'code',
        'description',
        'owner',
      )
    );
  }

  public function clear() {

    $this->code = self::CODE_DEFAULT;
    $this->description = self::DESCRIPTION_DEFAULT;
    $this->owner = null;
    $this->trace = array();
  }

  public function trace($text) {

    if (is_array($text)) {
      foreach ($text as $item) {
        $this->_trace[] = $item;
      }
    } else {
      $this->_trace[] = $text;
    }
  }

  public function merge(Error $error) {

    $data = $error->toArray();
    $count = 0;

    if (count($data['trace']) > 0) {
      foreach ($data['trace'] as $trace) {
        $this->trace($trace);
        $count++;
      }
    }

    if ($data['description']) {
      $this->trace($data['description']);
      $count++;
    }

    return $count;
  }

  public function display($html = true) {

    if ($html) { echo('<pre>'); }
    echo('Trace for owner ' . ($this->owner ? $this->owner : 'global') . ' at ' . date('Y-m-d H:i:s') . " {\r\n");
    echo('  Code #' . $this->code . ': ' . $this->description . "\r\n");
    foreach ($this->_trace as $text) {
      echo('  : ' . $text . "\r\n");
    }
    echo("}\r\n");
    if ($html) { echo('</pre>'); }
    return true;
  }

  public function toArray() {

    return array(
      'code' => $this->code,
      'description' => $this->description,
      'owner' => $this->owner,
      'trace' => $this->_trace,
    );
  }

  public function toJson() {

    return json_encode($this->toArray());
  }
}